package com.nx.platform.entry.utility;

import com.nx.arch.jodis.RoundRobinJedisPool;
import com.nx.arch.redis.clients.jedis.Jedis;
import com.nx.platform.entry.config.ApolloConfigItems;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 18-4-19 下午6:51 by nx
 ***/

@Slf4j
@Component
public class RedisUtil {

    @Autowired
    ApolloConfigItems apolloConfigItems;

    private static RoundRobinJedisPool roundRobinJedisPool = null;
    public void init(){
        String redisAppKey = apolloConfigItems.getRedisAppKey();
        String zkProxyDir = apolloConfigItems.getZkProxyDir();
        String curatorClient = apolloConfigItems.getCuratorClient();
        String redisPassWord = apolloConfigItems.getRedisPassWord();
        if (StringUtils.isEmpty(redisPassWord)) {
            redisPassWord = null;//因为测试环境不能设置密码
        }
        log.info(
                "act=start_init_redis_pool startTime=" , System.currentTimeMillis(),
                " redisPassWord=",redisPassWord,
                " redisAppKey=",redisAppKey,
                " zkProxyDir=",zkProxyDir,
                " curatorClient=",curatorClient );
        if(null == roundRobinJedisPool){
            roundRobinJedisPool = RoundRobinJedisPool.create()
                    .curatorClient(curatorClient, 2000)
                    .zkProxyDir(zkProxyDir).team("arch")
                    .connectionTimeoutMs(1000)
                    .soTimeoutMs(1000)//sockt超时时间，如果出现read time out ,请修改这个值
                    .appKey(redisAppKey)  //升级1：需要appkey权限认证
                    .password(redisPassWord) //升级2： 需要密码才能访问
                    //.poolConfig(poolConfig )//如果没有填，则均取默认值
                    .trickPrepare(true)//连接池初始化时新增 trickPrepare(true) 方法，可在执行build() 时马上建立链接
                    .build();
        }
        log.info("act=end_init_redis_pool endTime=" + System.currentTimeMillis());
    }

    public static Jedis getJedis() throws Exception{
        if(null != roundRobinJedisPool){
            return roundRobinJedisPool.getResource();
        }
        throw  new Exception("redis 连接池是null!");
    }

}
